package _17_函数式编程.Lambda._9_Lambda应用;

import _17_函数式编程.Lambda.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

public class _9_1_Lambda应用_Predicate_Consumer_Function {

    public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(
                new Apple("red",150),
                new Apple("green",234),
                new Apple("green",123)
        );

        List<Apple> result;

        //Predicate
        result = filter(appleList,
                (Apple apple) -> "green".equals(apple.getColor())
                );

        //Consumer
        printByConsumer(result,
                (Apple apple) -> System.out.println("苹果的颜色：" + apple.getColor() + "，重量：" + apple.getWeight())
        );

        //Function
        printByFunction(result,
                (Apple apple) -> "苹果的颜色：" + apple.getColor() + "，重量：" + apple.getWeight()
                );


    }



    public static <T> List<T> filter(List<T> list, Predicate<T> predicate){
        List<T> result = new ArrayList<>();
        for (T t : list){
            if(predicate.test(t)){
                result.add(t);
            }
        }
        return result;
    }

    public static <T> void printByConsumer(List<T> list, Consumer<T> consumer){
        for (T t : list){
            consumer.accept(t);
        }
    }

    public static <T,R> void printByFunction(List<T> list, Function<T,R> function){
        for (T t : list){
            R r = function.apply(t);
            System.out.println(r);
        }
    }



}
